#include "Viewer.h"
#include "Cube.h"
#include "Sphere.h"
#include "Plane.h"
#include "../common/elementconfig.h"
#include "stdio.h"

using namespace std;
using namespace qglviewer;

Viewer::Viewer(QWidget *parent)
    : QGLViewer(QGLFormat(QGL::SampleBuffers |
		QGL::DoubleBuffer |
		QGL::DepthBuffer |
		QGL::Rgba |
		QGL::AlphaChannel |
		QGL::StencilBuffer),parent)
{
}

Viewer::~Viewer()
{
}

void Viewer::init()
{
    //printf("init\n");
    Vec center(0.0, 0.0, 0.0);
    setSceneRadius(25.0);
    setSceneCenter(center);
    showEntireScene();

    // Setup OpenGL
    GLfloat ambient[] = { 0.3f, 0.3f, 0.3f };
    GLfloat diffuse[] = { 0.1f, 0.1f, 0.1f , 1.0f};
    GLfloat specular[] = { 0.0f, 0.0f, 0.0f , 1.0f};
    glLightfv(GL_LIGHT0, GL_AMBIENT, ambient);
    glLightfv(GL_LIGHT0, GL_DIFFUSE, diffuse);	
    glLightfv(GL_LIGHT0, GL_SPECULAR, specular);	

    startAnimation();
}
void Viewer::draw()
{
    foreach (Element *o,_elements)
    {
	o->render();
    }

    foreach (Element *o, _staticElements)
    {
        o->render();
    }
}
void Viewer::startAnimation()
{
    QGLViewer::startAnimation();
}
void Viewer::animate()
{
    // nothing spec
}

void Viewer::addElement(ElementType type, float *m, unsigned char *c, float *d)
{
    switch (type)
    {
    case CubeType:
        {
        printf("New Cube\n");
        Element *cube = new Cube(d, c, m);
        _elements.push_back(cube);
        break;
    }
    case SphereType:
        {
        printf("New Sphere\n");
        Element *sphere = new Sphere(d, c, m);
        _elements.push_back(sphere);
        break;
    }
    default:
        printf("fail?\n");
        break;
    }

}

void Viewer::UpdateObjects(float *m)
{
    int i = 0;
    foreach (Element *o, _elements)
    {
        o->setTransMatrix(&m[i * 4 * 4]);
        ++i;
    }
}

void Viewer::addElement(Element *e)
{
    _elements.push_back(e);
}

void Viewer::addStaticElement(Element *e)
{
    _staticElements.push_back(e);
}
void Viewer::clear(){
    _elements.clear();
}
